/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package soft.hb.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import soft.hb.R;
import soft.hb.model.Discharge;
import soft.hb.model.User;
import soft.hb.util.HttpRequest;
import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.ui.DatePickerWindow;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.TimeUtil;

/**
 * 排放超标车辆检查
 *
 * @author yuanweiwei
 */
public class DischargeActivity extends BaseActivity implements OnClickListener, OnHttpResponseListener, AlertDialog.OnDialogButtonClickListener  {
    public static final String TAG = "DischargeActivity";

    /**
     * 获取启动IndexActivity的intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, DischargeActivity.class);
    }


    @Override
    public Activity getActivity() {
        return this; //必须return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discharge_activity);
        intent = getIntent();

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private EditText editNumber;//编号
    private EditText editPlateNumber;//车辆牌照
    private EditText editManufacture;//车辆执照企业
    private EditText editModel;//车辆型号
    private EditText editSubordinateUnit;//所属单位
    private EditText editRegisteredAddress;//注册登记地
    private EditText editRegisteredDate;//注册登记日期
    private EditText editPlaceOfDeparture; //出发地
    private EditText editDestination; //目的地
    private EditText editDrive;//行驶主要道路及省市
    private EditText editPosition;//加油点位置
    private EditText editGasStation;//加油点名称
    private EditText editInspectionAgencyPosition;//排放检验机构位置（津籍车）
    private EditText editInspectionAgencyName;//排放检验机构名称
    private EditText editDistrict; //所在行政区
    private EditText editCheckTime; //检查时间
    private EditText editCheckAddress; //检查地点
    private EditText editCheckPeople;//检查人
    private EditText editCheckisReturnResult;//烟度检查结果
    private CheckBox cbIsReturnYes;
    private CheckBox cbIsReturnNo;


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initView() {//必须调用
        editNumber = findView(R.id.edit_number);
        editPlateNumber = findView(R.id.edit_plateNumber);
        editManufacture = findView(R.id.edit_manufacture);
        editModel = findView(R.id.edit_model);
        editSubordinateUnit = findView(R.id.edit_subordinateUnit);
        editRegisteredAddress = findView(R.id.edit_registeredAddress);
        editRegisteredDate = findView(R.id.edit_registeredDate);
        editRegisteredDate.setOnClickListener(this);
        editPlaceOfDeparture = findView(R.id.edit_placeOfDeparture);
        editDestination = findView(R.id.edit_destination);
        editDrive = findView(R.id.edit_drive);
        editPosition = findView(R.id.edit_position);
        editGasStation = findView(R.id.edit_gasStation);
        editInspectionAgencyPosition = findView(R.id.edit_inspectionAgencyPosition);
        editInspectionAgencyName = findView(R.id.edit_inspectionAgencyName);
        editDistrict = findView(R.id.edit_district);
        editCheckTime = findView(R.id.edit_checkTime);
        editCheckAddress = findView(R.id.edit_checkAddress);
        editCheckisReturnResult = findView(R.id.edit_checkisReturnResult);
        editCheckPeople = findView(R.id.edit_checkPeople);
        editCheckPeople.setOnClickListener(this);
        findView(R.id.btn_submit).setOnClickListener(this);

        cbIsReturnYes = findView(R.id.cb_isReturn_yes);
        cbIsReturnYes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    cbIsReturnNo.setChecked(false);
                }
            }
        });
        cbIsReturnNo = findView(R.id.cb_isReturn_no);
        cbIsReturnNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    cbIsReturnYes.setChecked(false);
                }
            }
        });

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    private static String[] TOPBAR_COLOR_NAMES = null;
    private static List<User> DATA_USER = new ArrayList<>();
    //勘验记录
    private static Discharge discharge = new Discharge();

    @Override
    public void initData() {//必须调用
        showProgressDialog(R.string.loading);
        HttpRequest.getUserList(0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                JSONObject jsonObject = JSON.parseObject(resultJson);
                JSONArray data = jsonObject == null ? null : jsonObject.getJSONArray("data");
                Log.i(TAG, data.toJSONString());
                if (data != null && data.size() > 0) {
                    TOPBAR_COLOR_NAMES = new String[data.size()];
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject jo = data.getJSONObject(i);
                        User user = JSON.parseObject(jo, User.class);
                        DATA_USER.add(user);
                        TOPBAR_COLOR_NAMES[i] = user.getName();
                    }
                }
                dismissProgressDialog();
            }
        });

        Calendar calendar = Calendar.getInstance();
        //获取系统的日期
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //获取系统时间
        //小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //分钟
        int minute = calendar.get(Calendar.MINUTE);
        editCheckTime.setText(year + "-" + month + "-" + day + "  " + hour + ":" + minute);
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须调用
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (! isPositive) {
            return;
        }

        switch (requestCode) {
            case 0:
                discharge.setNumber(editNumber.getText().toString());
                discharge.setPlateNumber(editPlateNumber.getText().toString());
                discharge.setManufacture(editManufacture.getText().toString());
                discharge.setModel(editModel.getText().toString());
                discharge.setSubordinateUnit(editSubordinateUnit.getText().toString());
                discharge.setRegisteredAddress(editRegisteredAddress.getText().toString());
                discharge.setRegisteredDate(editRegisteredDate.getText().toString());
                discharge.setPlaceOfDeparture(editPlaceOfDeparture.getText().toString());
                discharge.setDestination(editDestination.getText().toString());
                discharge.setDrive(editDrive.getText().toString());
                discharge.setPosition(editPosition.getText().toString());
                discharge.setGasStation(editGasStation.getText().toString());
                discharge.setInspectionAgencyPosition(editInspectionAgencyPosition.getText().toString());
                discharge.setInspectionAgencyName(editInspectionAgencyName.getText().toString());
                discharge.setDistrict(editDistrict.getText().toString());
                discharge.setCheckTime(editCheckTime.getText().toString());
                discharge.setCheckAddress(editCheckAddress.getText().toString());
                discharge.setCheckPeople(editCheckPeople.getText().toString());
                discharge.setCheckisReturnResult(editCheckisReturnResult.getText().toString());

                if (cbIsReturnYes.isChecked()){
                    discharge.setIsReturn("1");
                }

                if (cbIsReturnNo.isChecked()){
                    discharge.setIsReturn("2");
                }


                showProgressDialog(R.string.loading);
                HttpRequest.submitDischarge(discharge, 0, new OnHttpResponseListener() {
                    @Override
                    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                        dismissProgressDialog();
                        Log.i(TAG,resultJson);
                        JSONObject jsonObject = JSON.parseObject(resultJson);
                        if(jsonObject.getBoolean("success")){
                            //提交成功
                            showShortToast(R.string.add_succeed);
                            finish();
                        }else{
                            showShortToast(jsonObject.getString("msg"));
                        }
                    }
                });
                break;
            default:
                break;
        }
    }


    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private int[] selectedDate = new int[]{1971, 0, 1};
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                new AlertDialog(this, "提交记录", "确定表单是否填写完整并提交？", true, 0, this).show();
                break;

            case R.id.edit_checkPeople:
                if (TOPBAR_COLOR_NAMES != null && TOPBAR_COLOR_NAMES.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_COLOR_NAMES)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择检查人员"), REQUEST_TO_BOTTOM_MENU, false);
                }
                break;

            case R.id.edit_registeredDate:
                toActivity(DatePickerWindow.createIntent(context, new int[]{1971, 0, 1}
                        , TimeUtil.getDateDetail(System.currentTimeMillis())), REQUEST_TO_DATE_PICKER, false);
                break;
        }
    }


    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private static final int REQUEST_TO_BOTTOM_MENU = 1;
    private static final int REQUEST_TO_DATE_PICKER = 33;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_BOTTOM_MENU:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editCheckPeople.setText(DATA_USER.get(position).getName());
                        discharge.setCheckPeople(DATA_USER.get(position).getStrId());
                    }
                }
                break;
            case REQUEST_TO_DATE_PICKER:
                if (data != null) {
                    ArrayList<Integer> list = data.getIntegerArrayListExtra(DatePickerWindow.RESULT_DATE_DETAIL_LIST);
                    if (list != null && list.size() >= 3) {

                        selectedDate = new int[list.size()];
                        for (int i = 0; i < list.size(); i++) {
                            selectedDate[i] = list.get(i);
                        }
                        discharge.setRegisteredDate(selectedDate[0] + "-" + (selectedDate[1] + 1) + "-" + selectedDate[2]);
                        editRegisteredDate.setText(selectedDate[0] + "-" + (selectedDate[1] + 1) + "-" + selectedDate[2]);
                    }
                }
                break;
        }
    }


    @Override
    public void finish() {
        super.finish();

    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {

    }


    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


}